<template>
	<view class="profile-page">
		<view class="user-card">
			<image class="avatar" :src="getAvatarUrl(userInfo.avatarUrl)" mode="aspectFill" />
			<view class="meta">
				<text class="nickname">{{ userInfo.nickname || '未设置昵称' }}</text>
				<text v-if="userInfo.phone" class="phone">{{ userInfo.phone }}</text>
				<text v-else class="phone none">绑定手机享更多权益</text>
			</view>
			<button 
				class="settings-btn" 
				:class="{ disabled: !isLogin }"
				:disabled="!isLogin"
				@click="goSetting"
			>设置</button>
		</view>

		<view class="card" v-if="isLogin">
			<view class="card-header">
				<text class="card-title">我的订单</text>
				<text class="card-action" @click="goOrder('all')">查看全部</text>
			</view>
			<view class="order-grid">
				<view class="order-item" v-for="item in orderNavs" :key="item.key" @click="goOrder(item.key)">
					<text class="icon">{{ item.icon }}</text>
					<text class="label">{{ item.label }}</text>
					<view v-if="orderSummary[item.key]" class="badge">{{ orderSummary[item.key] }}</view>
				</view>
			</view>
		</view>

		<view class="card" v-if="isLogin">
			<view class="card-header">
				<text class="card-title">我的服务</text>
			</view>
			<view class="tool-grid">
				<view class="tool-item" v-for="tool in toolNavs" :key="tool.key" @click="goTool(tool)">
					<view class="tool-icon" :style="{ background: tool.bg }">{{ tool.icon }}</view>
					<text class="tool-label">{{ tool.label }}</text>
					<view v-if="toolSummary[tool.key]" class="dot">{{ toolSummary[tool.key] }}</view>
				</view>
			</view>
		</view>

		<view class="auth-card" v-if="!isLogin">
			<text class="auth-title">登录后解锁专属权益</text>
			<input class="auth-input" placeholder="用户名" v-model="form.username" />
			<input class="auth-input" placeholder="密码" password v-model="form.password" />
			<view class="auth-actions">
				<button class="auth-btn primary" @click="login">登录</button>
				<button class="auth-btn ghost" @click="register">注册</button>
			</view>
		</view>

		<view class="logout" v-else>
			<button class="logout-btn" @click="logout">退出登录</button>
		</view>
	</view>
</template>

<script>
import { request, api } from '../../utils/request.js'
import { BASE_URL } from '../../utils/server.js'

export default {
	data() {
		return {
			defaultAvatar: 'https://dummyimage.com/200x200/ffb347/ffffff.png&text=HD',
			isLogin: false,
			form: {
				username: '',
				password: ''
			},
			userInfo: {},
			orderSummary: {
				all: 0,
				pendingPay: 0,
				pendingShip: 0,
				pendingReceive: 0,
				pendingComment: 0
			},
			toolSummary: {
				favorite: 0,
				coupon: 0,
				share: 0,
				address: 0,
				refund: 0
			},
			orderNavs: [
				{ key: 'all', label: '全部订单', icon: '📦' },
				{ key: 'pendingPay', label: '待付款', icon: '💳' },
				{ key: 'pendingShip', label: '待发货', icon: '🚚' },
				{ key: 'pendingReceive', label: '待收货', icon: '📮' },
				{ key: 'pendingComment', label: '待评价', icon: '📝' }
			],
			toolNavs: [
				{ key: 'favorite', label: '商品收藏', icon: '❤', bg: 'linear-gradient(135deg,#D0E5FF,#C0DBFF)', url: '' },
				{ key: 'coupon', label: '优惠券', icon: '🎟', bg: 'linear-gradient(135deg,#C8E0FF,#B8D5FF)', url: '' },
				{ key: 'share', label: '分享好礼', icon: '🎁', bg: 'linear-gradient(135deg,#D8EBFF,#C8E0FF)', url: '' },
				{ key: 'address', label: '收货地址', icon: '📍', bg: 'linear-gradient(135deg,#D0E5FF,#C0DBFF)', url: '' },
				{ key: 'refund', label: '退款售后', icon: '🔁', bg: 'linear-gradient(135deg,#C8E0FF,#B8D5FF)', url: '' }
			]
		}
	},
	onShow() {
		this.init();
	},
	methods: {
		async init() {
			this.isLogin = !!uni.getStorageSync('token');
			if (this.isLogin) {
				await this.loadProfile();
			}
		},
		async loadProfile() {
			try {
				const res = await api.getUserProfile();
				if (res.code === 0) {
					this.userInfo = res.data.userInfo || {};
					this.orderSummary = { ...this.orderSummary, ...(res.data.orderSummary || {}) };
					this.toolSummary = { ...this.toolSummary, ...(res.data.toolSummary || {}) };
				} else if (res.code === 401) {
					this.handleSessionExpired();
				}
			} catch (err) {
				uni.showToast({ icon: 'none', title: '获取资料失败' });
			}
		},
		handleSessionExpired() {
			uni.removeStorageSync('token');
			this.isLogin = false;
			this.userInfo = {};
			uni.showToast({ icon: 'none', title: '登录已过期，请重新登录' });
		},
		async login() {
			if (!this.form.username || !this.form.password) {
				uni.showToast({ icon: 'none', title: '请输入账号密码' });
				return;
			}
			try {
				const res = await request({ url: '/api/users/login', method: 'POST', data: this.form });
				if (res.code === 0) {
					uni.setStorageSync('token', res.data.token);
					this.userInfo = res.data.user || {};
					this.isLogin = true;
					uni.showToast({ title: '登录成功' });
					this.loadProfile();
				} else {
					uni.showToast({ icon: 'none', title: res.message || '登录失败' });
				}
			} catch (err) {
				uni.showToast({ icon: 'none', title: '请求失败' });
			}
		},
		async register() {
			if (!this.form.username || !this.form.password) {
				uni.showToast({ icon: 'none', title: '请输入账号密码' });
				return;
			}
			try {
				const res = await request({ url: '/api/users/register', method: 'POST', data: this.form });
				if (res.code === 0) {
					uni.showToast({ title: '注册成功' });
				} else {
					uni.showToast({ icon: 'none', title: res.message || '注册失败' });
				}
			} catch (err) {
				uni.showToast({ icon: 'none', title: '请求失败' });
			}
		},
		logout() {
			uni.removeStorageSync('token');
			this.isLogin = false;
			this.userInfo = {};
			this.orderSummary = { all: 0, pendingPay: 0, pendingShip: 0, pendingReceive: 0, pendingComment: 0 };
			this.toolSummary = { favorite: 0, coupon: 0, share: 0, address: 0, refund: 0 };
			uni.showToast({ title: '已退出' });
		},
		goSetting() {
			if (!this.isLogin) {
				uni.showToast({ icon: 'none', title: '请先登录' });
				return;
			}
			uni.navigateTo({ url: '/pages/profile/settings' });
		},
		goOrder(key) {
			uni.navigateTo({ url: `/pages/order/index?tab=${key}` });
		},
		goTool(tool) {
			if (tool.key === 'favorite') {
				uni.navigateTo({ url: '/pages/favorite/index' });
				return;
			}
			if (tool.key === 'coupon') {
				uni.navigateTo({ url: '/pages/coupon/index' });
				return;
			}
			if (tool.key === 'share') {
				uni.navigateTo({ url: '/pages/share/index' });
				return;
			}
			if (tool.key === 'address') {
				uni.navigateTo({ url: '/pages/address/index' });
				return;
			}
			if (tool.key === 'refund') {
				uni.navigateTo({ url: '/pages/order/index?tab=refund' });
				return;
			}
			if (tool.url) {
				uni.navigateTo({ url: tool.url });
			} else {
				uni.showToast({ icon: 'none', title: `${tool.label} 敬请期待` });
			}
		},
		findLabel(list, key) {
			const item = list.find(i => i.key === key);
			return item ? item.label : '';
		},
		getAvatarUrl(url) {
			if (!url) return this.defaultAvatar;
			if (url.startsWith('http')) return url;
			return BASE_URL + url;
		}
	}
}
</script>

<style>
.profile-page { padding: 24rpx; background: #F0F7FF; min-height: 100vh; }
.user-card { display: flex; align-items: center; background: linear-gradient(120deg,#5B9BD5,#7BB3E8); padding: 32rpx 28rpx; border-radius: 28rpx; color: #fff; box-shadow: 0 12rpx 32rpx rgba(91,155,213,.25); margin-bottom: 32rpx; }
.avatar { width: 120rpx; height: 120rpx; border-radius: 50%; margin-right: 24rpx; border: 4rpx solid rgba(255,255,255,.6); }
.meta { flex: 1; }
.nickname { font-size: 36rpx; font-weight: 700; display: block; }
.phone { font-size: 26rpx; margin-top: 8rpx; display: block; }
.phone.none { opacity: .8; }
.settings-btn { border: none; background: rgba(255,255,255,.26); color: #fff; padding: 12rpx 28rpx; border-radius: 999rpx; font-size: 26rpx; }
.settings-btn.disabled { opacity: 0.5; background: rgba(255,255,255,.15); }
.settings-btn[disabled] { opacity: 0.5; background: rgba(255,255,255,.15); }
.card { background: #fff; border-radius: 24rpx; padding: 24rpx 28rpx; box-shadow: 0 8rpx 24rpx rgba(91,155,213,.1); margin-bottom: 28rpx; }
.card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20rpx; }
.card-title { font-size: 32rpx; font-weight: 600; color: #2C5F8D; }
.card-action { font-size: 26rpx; color: #5B9BD5; }
.order-grid { display: grid; grid-template-columns: repeat(5,1fr); gap: 12rpx; }
.order-item { position: relative; display: flex; flex-direction: column; align-items: center; padding: 16rpx 0; }
.order-item .icon { font-size: 40rpx; }
.order-item .label { margin-top: 10rpx; font-size: 24rpx; color: #4A6FA5; }
.badge { position: absolute; top: 6rpx; right: 28rpx; min-width: 28rpx; padding: 4rpx 8rpx; background: #00CED1; color: #fff; border-radius: 999rpx; font-size: 20rpx; text-align: center; }
.tool-grid { display: grid; grid-template-columns: repeat(5,1fr); gap: 16rpx; }
.tool-item { position: relative; display: flex; flex-direction: column; align-items: center; padding: 20rpx 0; }
.tool-icon { width: 100rpx; height: 100rpx; border-radius: 32rpx; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 40rpx; margin-bottom: 16rpx; box-shadow: 0 8rpx 20rpx rgba(91,155,213,.2); }
.tool-label { font-size: 24rpx; color: #4A6FA5; }
.dot { position: absolute; top: 12rpx; right: 36rpx; min-width: 30rpx; padding: 4rpx 10rpx; border-radius: 999rpx; background: #00CED1; color: #fff; font-size: 20rpx; text-align: center; }
.auth-card { background: #fff; border-radius: 24rpx; padding: 32rpx 28rpx; box-shadow: 0 8rpx 24rpx rgba(91,155,213,.1); }
.auth-title { font-size: 32rpx; font-weight: 600; color: #2C5F8D; margin-bottom: 24rpx; display: block; }
.auth-input { background: #E8F2FF; border-radius: 16rpx; padding: 20rpx 24rpx; margin-bottom: 20rpx; font-size: 28rpx; }
.auth-actions { display: flex; gap: 20rpx; }
.auth-btn { flex: 1; padding: 18rpx 0; border-radius: 16rpx; font-size: 28rpx; }
.auth-btn.primary { background: linear-gradient(135deg,#5B9BD5,#7BB3E8); color: #fff; border: none; }
.auth-btn.ghost { border: 2rpx solid #5B9BD5; color: #5B9BD5; background: #fff; }
.logout { margin-top: 40rpx; }
.logout-btn { width: 100%; border: 2rpx solid #5B9BD5; background: #fff; color: #5B9BD5; border-radius: 16rpx; padding: 18rpx 0; font-size: 28rpx; }
</style>